#coding=utf-8
'''
Created on 2017-6-15

@author: sandy
'''

import sys,platform
sys.path.append("../")
if 'twisted.internet.reactor' not in sys.modules: 
    if platform.system() == "Linux":
        from twisted.internet import epollreactor
        epollreactor.install()  
    else:
        from twisted.internet import iocpreactor
        iocpreactor.install()   
from twisted.internet import reactor
from pycommon import remotemanager,utils,daemon
import serverconfig

import proxyclientfactory
import TcpProxy  
import timecheck
 
def ServerStart(isdaemon):
    serverconfig.instance.loadFromFile()
    timecheck.instance.start()
    proxyclientfactory.instance.start(serverconfig.instance.proxy_ip,serverconfig.instance.proxy_port,serverconfig.instance.max_client)
    #TcpProxy.instance.start(serverconfig.instance.proxy_ip,serverconfig.instance.proxy_port)
    pass

def ServerStop():
    #TcpProxy.instance.stop()
    clientfactory.instance.stop()
    pass

def daemonFunc(isdaemon):
    remotemanager.instance.setupLog(isdaemon)
    ServerStart(isdaemon)
    reactor.run()
    ServerStop()

def run():
    sid, msip, msport, pidpath, logfile, loglevel, pathSelfConfig = utils.loadDaemonConfig(serverconfig.instance.rundir)
    remotemanager.instance.init(sid, msip, msport, logfile, loglevel, pathSelfConfig)
    daemon.run(pidpath, daemonFunc)
    
if __name__ == "__main__":
    run()
